package components.base
{
	import mx.collections.IList;
	import mx.events.FlexEvent;
	
	import spark.components.ComboBox;
	
	import components.custom.MultiSelectComboBoxDropDownCtrl;
	
	import framework.LangMgr;
	
	import interfaces.IReset;
	
	public class BaseComboBox extends ComboBox implements IReset
	{
		/**值域**/
		public var valueField:String;
		
		private var _defaultItemKey:String;
		public function set defaultItemKey(p_str:String):void
		{
			_defaultItemKey = p_str;
			addDefaultItem();
		}
		public function get defaultItemKey():String
		{
			return _defaultItemKey;
		}
		
		/**
		 * 添加默认项
		 */
		protected function addDefaultItem():void
		{
			if(!_defaultItemKey)return;
			var str:String = LangMgr.getResourceByLocaleKey(_defaultItemKey);
			if(!str)return;
			var dp:IList = dataProvider;
			if(dp.length > 0){
				var obj:Object = dp.getItemAt(0);
				//已经添加默认项，直接返回
				if(obj[labelField] && obj[labelField] == str)
					return;
			}
			var item:Object = {};
			item[labelField] = str;
			dp.addItemAt(item, 0);
		}
		
		public function BaseComboBox()
		{
			super();
			super.dropDownController = new MultiSelectComboBoxDropDownCtrl();
			addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);
		}
		
		/**
		 * 控件创建完成后调用初始化信息
		 */
		private function creationCompleteHandler(p_evt:FlexEvent):void
		{
			removeEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);
			if(styleName == null)
				styleName = "comboBox";
		}
		
		public function dispose():void
		{
			
		}
		
		public function reset():void
		{
			selectedIndex = 0;
		}
		
		/***
		 * 当前选中的值
		 * */
		[Bindable("change")]
		[Bindable("valueCommit")]
		[Inspectable(category="General")]
		public function get selectedValue():String
		{
			var obj:Object = super.selectedItem;
			if(!obj)return null;
			if(valueField){
				if(obj && obj.hasOwnProperty(valueField))
					return obj[valueField];
				else
					return null;
			}
			return String(obj);
		}
		public function set selectedValue(value:String):void
		{
			if(valueField){
				if(dataProvider && dataProvider.length > 0){
					for(var i:int = 0;i < dataProvider.length;i++){
						var item:Object = dataProvider.getItemAt(i);
						if(item.hasOwnProperty(valueField) && item[valueField] == value){
							super.selectedItem = item;
							break;
						}
					}
				}
			}else{
				super.selectedItem = value;
			}
		}
	}
}